<script setup lang="ts">
import type { FormInstance, FormValidateCallback, UploadFile, UploadFiles } from 'element-plus'
import type { EaWelfare } from './type'
import { uploadFile } from '@/api'
const baseApi = '/ea/ea-welfare'

defineProps<{
  // 禁用表单内的所有组件
  disabled?: boolean
  // 禁用属性列表（只读不可输入）
  disabledProps?: string[]
  // 不可见属性列表（忽略不加载）
  invisibleProps?: string[]
}>()

const emit = defineEmits<{
  (e: 'complete', id?: string, isNew?: boolean): void
  (e: 'submitting', submitting: boolean): void
}>()

const { loadData, loading, model } = useDetail<EaWelfare>(baseApi)
const { submitting, submit } = useForm({ baseApi, successCallback: (id, isNew) => emit('complete', id, isNew) })
watch(submitting, value => emit('submitting', value))

//  表单
const formRef = ref<FormInstance>()

const skipTypeList = ref<LabelValue[]>([
  {
    label: '微信',
    value: 'wx'
  },
  {
    label: '邀请',
    value: 'invite'
  },
  {
    label: '视频',
    value: 'video'
  }
])
const welfareTypeList = ref<LabelValue[]>([
  {
    label: '活动',
    value: 'Events'
  },
  {
    label: '福利',
    value: 'Bonus'
  }
])
// 文件列表
const pic = ref<UploadFiles>([])
const wxPic = ref<UploadFiles>([])

// 上传文件
const mainUpload = async options => {
  try {
    const res = await uploadFile(options.file)
    if (res.data) {
      model.value.pic = res.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    // 上传失败时移除文件
    const index = pic.value.findIndex(item => item.uid === options.file.uid)
    if (index !== -1) {
      pic.value.splice(index, 1)
    }
  }
}
const wxUpload = async options => {
  try {
    const res = await uploadFile(options.file)
    if (res.data) {
      model.value.wxPic = res.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    // 上传失败时移除文件
    const index = wxPic.value.findIndex(item => item.uid === options.file.uid)
    if (index !== -1) {
      wxPic.value.splice(index, 1)
    }
  }
}

// 文件移除时处理
const handleFileRemove = (file, fileList) => {
  pic.value = fileList.filter(item => item.uid !== file.uid)
  model.value.pic = '' // 移除文件时清空表单中的值
}

const handleWxFileRemove = (file, fileList) => {
  wxPic.value = fileList.filter(item => item.uid !== file.uid)
  model.value.wxPic = '' // 移除文件时清空表单中的值
}

const validate = (
  callback: FormValidateCallback = (valid: boolean) =>
    !valid && ElMessage.error({ message: '表单校验不通过', grouping: true })
) =>
  Promise.all([formRef.value].map(e => e?.validate?.(callback)).filter(e => !!e))
    .then((arr: (boolean | undefined)[]) => arr.every(e => e))
    .catch(() => false)

defineExpose({
  init: (id?: string, refresh = true, initData?: Record<string, unknown>) => {
    if (model.value.id === id && !refresh) return

    // 加载数据
    loadData(id).then(() => {
      if (model.value.pic) {
        pic.value = [
          {
            name: String(new Date().getTime()),
            url: model.value.pic,
            status: 'success',
            uid: Date.now()
          }
        ]
      }
      if (model.value.wxPic) {
        wxPic.value = [
          {
            name: String(new Date().getTime()),
            url: model.value.wxPic,
            status: 'success',
            uid: Date.now()
          }
        ]
      }
      if (!id) {
        if (initData) Object.keys(initData).forEach(key => (model.value[key as keyof EaWelfare] = initData[key] as any))
      }
    })
  },
  validate,
  getData: async (relatedLabel = false) => {
    const data: Record<string, unknown> = _.cloneDeep(model.value)
    if (!relatedLabel) return data

    return data
  },
  submit: async () => {
    // const uploadPromises = mainPic.value.map(file => uploadToOSS(file))
    // const urls = await Promise.all(uploadPromises)
    // if (urls.length > 0) {
    //   model.value.pic = urls[0]
    // } else {
    //   model.value.pic = ''
    // }
    // const wxUploadPromises = wxPic.value.map(file => uploadToOSS(file))
    // const wxUrls = await Promise.all(wxUploadPromises)

    // if (wxUrls.length > 0) {
    //   model.value.wxPic = wxUrls[0]
    // } else {
    //   model.value.wxPic = ''
    // }

    // 这里可以提交表单数据到后端

    submit(model.value, formRef.value)
  },
  reset: () => {
    formRef.value?.resetFields()
    model.value.id = void 0
  }
})
</script>

<template>
  <el-form ref="formRef" v-loading="loading" :model="model" label-width="120" :disabled="disabled">
    <el-row :gutter="18">
      <el-col v-if="!invisibleProps?.includes('title')" :span="24">
        <el-form-item prop="title" label="标题">
          <el-input v-model="model.title" :disabled="disabledProps?.includes('title')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('content')" :span="24">
        <el-form-item prop="content" label="详情">
          <el-input v-model="model.content" :disabled="disabledProps?.includes('content')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('wxPic')" :span="24">
        <el-form-item prop="wxPic" label="微信群聊截图">
          <el-upload
            v-model:file-list="wxPic"
            :http-request="wxUpload"
            :on-remove="handleWxFileRemove"
            :limit="1"
            list-type="picture"
          >
            <el-button v-if="!model.wxPic" size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('pic')" :span="24">
        <el-form-item prop="pic" label="列表图片">
          <el-upload
            v-model:file-list="pic"
            :http-request="mainUpload"
            :on-remove="handleFileRemove"
            :limit="1"
            list-type="picture"
          >
            <el-button v-if="!model.pic" size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('skipType')" :span="24">
        <!-- <el-form-item prop="skipType" label="跳转类型">
          <el-input v-model="model.skipType" :disabled="disabledProps?.includes('skipType')" clearable />
        </el-form-item> -->

        <el-form-item prop="skipType" label="跳转类型">
          <el-select v-model="model.skipType" filterable clearable>
            <el-option v-for="item in skipTypeList" :key="item.value" v-bind="item" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('welfareType')" :span="24">
        <el-form-item prop="welfareType" label="福利类型">
          <el-select v-model="model.welfareType" filterable clearable>
            <el-option v-for="item in welfareTypeList" :key="item.value" v-bind="item" />
          </el-select>

          <!-- <el-input v-model="model.welfareType" :disabled="disabledProps?.includes('welfareType')" clearable /> -->
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('sort')" :span="24">
        <el-form-item prop="sort" label="排序">
          <el-input v-model="model.sort" :disabled="disabledProps?.includes('sort')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('status')" :span="24">
        <el-form-item prop="status" label="状态">
          <el-input v-model="model.status" :disabled="disabledProps?.includes('status')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('startTime')" :span="24">
        <el-form-item prop="startTime" label="开始时间">
          <el-input v-model="model.startTime" :disabled="disabledProps?.includes('startTime')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('endTime')" :span="24">
        <el-form-item prop="endTime" label="结束时间">
          <el-input v-model="model.endTime" :disabled="disabledProps?.includes('endTime')" clearable />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
